#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>

#define CMD_IOC_MAGIC	'a'
#define CMD_IOC_0		_IO(CMD_IOC_MAGIC, 0)
#define CMD_IOC_1		_IOR(CMD_IOC_MAGIC, 1, int)
#define CMD_IOC_2		_IOW(CMD_IOC_MAGIC, 2, int)


int main(int argc,char*argv[])
{
	int rc;
	int arg_r;
	const int arg_w = 255;
	int fd = open("/dev/test_chr_dev", O_RDWR);
	if (fd < 0) 
	{
		printf("open DEVICE_ATTR failed!\n");
	}
	if(argc>=2)
	{
		
		if(strcmp(argv[1],"-1")==0)
		{
			rc = ioctl(fd, CMD_IOC_1,arg_r);
			printf("choose mode 1\n");
		}
		else if(strcmp(argv[1],"-2")==0)
		{
			rc = ioctl(fd, CMD_IOC_2,arg_w);
			printf("choose mode 2\n");
		}

	}
	close(fd);

	int   fdx;
	char *buf = "xxxxxxxxx xxx!";
	fdx        = open("./file1",O_RDWR);
	if(fdx == -1)
	{
		printf("open file1 fail!!\n");
		fdx = open("./file1",O_RDWR|O_CREAT,0600);
		if(fdx > 0)
		{
			printf("create file1 success!!!\n");
		}
		else if(fdx == -1)
		{
		printf("creat file1 success!!\n");
		}
	}
	else
	{
		// printf("open file1 success!!!\n");
	}
	int n_write = write(fdx,argv[2],strlen(argv[2]));
	if(n_write != -1)
	{
		printf("write %d byte to file1\n",n_write);
	}
	else
	{
		printf("write fail!!!\n");
	}
	
	char    *readBuf;
	readBuf = (char*)malloc(sizeof(char)*n_write);
	close(fdx);
	open("./file1",O_RDWR);
	int n_read = read(fdx,readBuf,n_write);


	if(strcmp(argv[1],"-1")==0)
	{
    	char readBuf_temp[n_read+1];
    	for(int i=n_read-1;i>=0;i--)
		{
			readBuf_temp[n_read-1-i]=*(readBuf+i);
		}   
    	readBuf_temp[n_read+1]='\0';
		printf("context = %s\n",readBuf_temp);
	}
	else if(strcmp(argv[1],"-2")==0)
	{
		printf("context = %s\n",readBuf);
	}    
	else
	{
        printf("input fail!!!\n");
	}

	close(fdx);
 
	return 0;
}
